package com.leetcode;

import com.leetcode.common.TreeNode;
import com.leetcode.util.BinaryTreeUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 102. 二叉树的层序遍历
 * 递归深度优先搜索, 传递节点所在的层
 *
 * @author fy
 * @date 2022/4/15 8:46
 */
public class Solution102_2 {

    private List<List<Integer>> res;

    public List<List<Integer>> levelOrder(TreeNode root) {
        res = new ArrayList<>();
        // 可以不用对root进行判空操作
//        if (root == null) {
//            return res;
//        }
        dfs(root, 0);
        return res;
    }

    private void dfs(TreeNode node, int level) {
        if (node == null) {
            return;
        }
        if (level == res.size()) {
            res.add(new ArrayList<>());
        }
        res.get(level).add(node.val);
        dfs(node.left, level + 1);
        dfs(node.right, level + 1);
    }

    public static void main(String[] args) {
        Integer[] nums = new Integer[]{3, 9, 20, null, null, 15, 7};
        TreeNode root = BinaryTreeUtil.createTree(nums);
        BinaryTreeUtil.printTree(root);

        List<List<Integer>> res = new Solution102_2().levelOrder(root);
        System.out.println(res);
    }
}
